<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\Admin;

use App\Constants\ListenerConst;
use App\Middleware\Auth\RefreshTokenMiddleware;
use App\Service\AdminUserService;
use Hyperf\Cache\Listener\DeleteListenerEvent;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\PostMapping;
use Psr\Http\Message\ResponseInterface;

/**
 * 后台用户
 * Class AdminUserController.
 */
#[Controller(prefix: 'admin/admin_user')]
class AdminUserController extends MainController
{
    #[Inject]
    protected AdminUserService $adminUserService;

    #[PostMapping(path: 'login')]
    public function login(): ResponseInterface
    {
        $credentials = $this->request->inputs(['username', 'password']);
        if (!$token = auth('admin')->attempt([
            'username' => (string)$credentials['username'],
            'password' => (string)$credentials['password'],
        ])) {
            return $this->error('账号/密码错误');
        }
        return $this->success([
            'token' => $token,
        ]);
    }

    /**
     * 账户是否注册.
     */
    #[GetMapping(path: 'login')]
    public function accountExist(): ResponseInterface
    {
        $name = $this->request->query('name', '');

        return $this->success([
            'exist' => $this->adminUserService->existUser($name),
        ]);
    }

    /**
     * 获取用户信息.
     */
    #[Middlewares([RefreshTokenMiddleware::class])]
    #[PostMapping(path: 'getInfo')]
    public function getInfo(): ResponseInterface
    {
        $data = $this->adminUserService->getInfo();

        return $this->success($data);
    }

    /**
     * 退出登录.
     */
    #[PostMapping(path: 'logout')]
    public function logout(): ResponseInterface
    {
        if ($userId = userID()) {
            event(new DeleteListenerEvent(ListenerConst::USER_UPDATE, ['userId' => $userId]));
            auth('admin')->logout();
        }
        return $this->success([], '登出成功');
    }

    /**
     * 手动签发.
     */
    #[PostMapping(path: 'manualLogin')]
    public function manualLogin(): ResponseInterface
    {
        $token = $this->adminUserService->toIssued(2);
        return $this->success([
            'token' => $token,
        ]);
    }
}
